package com.aoxin.util.weiXinPay.weiXinSina;

import java.util.*;
import java.util.Map.Entry;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.aoxin.util.md5.MD5;
import com.aoxin.util.md5.Md5Util;
import com.aoxin.util.weiXinPay.WeiXinPayConfig;
import com.aoxin.util.weiXinPay.sortUntil.SortUtil;
import org.springframework.util.StringUtils;


public class Sina {
	@SuppressWarnings("unchecked")
	public static String getSina(Map<String, Object> map) {
        //字典排序
        List<String> list = new ArrayList<>();
        removeNullValue(map);
        for (Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (key != null && value != null) {
                list.add(key);
                list = SortUtil.sortList(list);
            }
        }
        String sortStr = "";
        for (int i = 0; i < list.size(); i++) {
            String value = map.get(list.get(i)).toString();
            String key = list.get(i);
            sortStr += key + "=" + value + "&";
        }
        System.out.println("排序后:"+sortStr);
        String stringSignTemp = "";
        // 拼接秘钥
        stringSignTemp = sortStr + "key=" + WeiXinPayConfig.key;
        // md5加密
        String sina = "";
        sina = Md5Util.md5(stringSignTemp).toUpperCase();
        //sha256_HMAC
        String sha256_HMAC = sha256_HMAC(sina, WeiXinPayConfig.key).toUpperCase();
        System.out.println("sha256_HMAC="+sha256_HMAC);
        return sina;
	}
	
	/**
	 *@方法名:sha256_HMAC
	 *@描述:
	 *@param message
	 *@param secret
	 *@return
	 */
	public static String sha256_HMAC(String message, String secret) {
		String hash = "";
		try {
			Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
			sha256_HMAC.init(secret_key);
			byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
			hash = byteArrayToHexString(bytes);
		} catch (Exception e) {
			System.out.println("Error HmacSHA256 ===========" + e.getMessage());
		}
		return hash;
	}
	/**
	 * 排序
	 *@方法名:byteArrayToHexString
	 *@描述:
	 *@param b
	 *@return
	 */
	public static String byteArrayToHexString(byte[] b) {
		StringBuilder hs = new StringBuilder();
		String stmp;
		for (int n = 0; b != null && n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1)
				hs.append('0');
			hs.append(stmp);
		}
		return hs.toString().toLowerCase();
	}
	/** 
     * 移除map中的value空值 
     * @param map 
     * @return 
     */  
    @SuppressWarnings("rawtypes")
	public static void removeNullValue(Map map){  
        Set set = map.keySet();  
        for (Iterator iterator = set.iterator(); iterator.hasNext();) {  
            Object obj = (Object) iterator.next();  
            Object value =(Object)map.get(obj);  
            remove(value, iterator);  
        }  
    }  
   
   @SuppressWarnings("rawtypes")
private static void remove(Object obj,Iterator iterator){  
       if(obj instanceof String){  
           String str = (String)obj;  
           if(StringUtils.isEmpty(str)){  
               iterator.remove();  
           }  
       }else if(obj instanceof Collection){  
           Collection col = (Collection)obj;  
           if(col==null||col.isEmpty()){  
               iterator.remove();  
           }  
             
       }else if(obj instanceof Map){  
           Map temp = (Map)obj;  
           if(temp==null||temp.isEmpty()){  
               iterator.remove();  
           }  
             
       }else if(obj instanceof Object[]){  
           Object[] array =(Object[])obj;  
           if(array==null||array.length<=0){  
               iterator.remove();  
           }  
       }else{  
           if(obj==null){  
               iterator.remove();  
           }  
       }  
   } 
   public static void main(String[] args) {
	   String md5 = MD5.md5("123");
	   System.out.println(md5+"size="+md5.length());
	   String upperCase = Md5Util.md5("123");
	   if("202cb962ac59075b964b07152d234b70".equals(upperCase)){
		   System.out.println("true");
	   }
}


    public static String createSign(SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + WeiXinPayConfig.key);
        String sign = Md5Util.md5(sb.toString()).toUpperCase();
        return sign;
    }
}

